package leetcode.editor.cn.util.tree.btree;

import java.util.ArrayDeque;
import java.util.Deque;

public class BTreeUtil {
    private static final BTreeUtil util = new BTreeUtil();

    private BTreeUtil() {
    }

    public static BTreeUtil getInstance() {
        return util;
    }

    public TreeNode generateFromArray(Integer... arr) {
        if (arr == null || arr.length == 0) return null;

        Deque<TreeNode> q = new ArrayDeque<>();
        TreeNode head = new TreeNode(arr[0]);
        q.add(head);

        for (int i = 1; i < arr.length; i += 2) {
            TreeNode node = q.poll();
            if (arr[i] != null) {
                node.left = new TreeNode(arr[i]);
                q.add(node.left);
            }
            if (i + 1 < arr.length && arr[i + 1] != null) {
                node.right = new TreeNode(arr[i + 1]);
                q.add(node.right);
            }
        }

        return head;
    }


    public static TreeNode generateFromArr(Integer... arr) {
        return BTreeUtil.getInstance().generateFromArray(arr);
    }

    public static void main(String[] args) {
        BTreeUtil.getInstance().generateFromArray(new Integer[]{1, null, 2, 3});
        BTreeUtil.getInstance().generateFromArray(new Integer[]{1, 2, 3, 4, 5, 6, 7});
    }
}
